/**
*  
* @Function 生成报告任务实体类 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.entity    
* @FileName CreateReportTask.java    
* @Date 2018年10月23日上午11:20:29
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/  
package com.py.credit.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.service.BatchReportDetailService;
import com.py.credit.service.CreditReportService;
import com.py.credit.service.SSearchService;
import com.py.credit.service.ScontentService;
import com.py.credit.service.impl.BgdzServiceImpl;
import com.py.credit.utils.DateUtils;
import com.py.credit.utils.FreeeMarkerUtils;
import com.py.credit.utils.HtmlToPdfUtils;

/**
 * 
 * @Function 生成报告任务实体类
 * @ClassName CreateReportTask
 * @Date 2018年10月23日 上午11:20:29
 * @Author Min DongXv
 * 
 */
public class CreateReportTask implements Callable<CreateReportResult> {

	/**
	 * 文件路径
	 */
	private String filePath;
	/**
	 * pdf转换脚本路径
	 */
	private String pdfJsPath;
	/**
	 * 谷歌浏览器路径
	 */
	private String googlePath;
	/**
	 * 生成报告页面路径
	 */
	private String pdfPagePath;

	private String absolutepath;

	/**
	 * 库ID
	 */
	private String kId;

	private BatchReportDetailEntity batchReportDetailEntity;

	private BatchReportDetailService batchReportDetailService;

	private CreditReportService creditReportService;

	private ScontentService sContentService;

	private SSearchService sSearchService;

	private BgdzServiceImpl bgdzService;

	/**
	* @Desc:
	* @author MaoLiliang
	* @param filePath
	* @param pdfJsPath
	* @param googlePath
	* @param pdfPagePath
	* @param absolutepath
	* @param kId
	* @param batchReportDetailEntity
	* @param batchReportDetailService
	* @return
	* @date 2020/12/29 15:54
	*/
	public CreateReportTask(String filePath, String pdfJsPath, String googlePath, String pdfPagePath, String absolutepath,
			String kId, BatchReportDetailEntity batchReportDetailEntity, BatchReportDetailService batchReportDetailService,
			CreditReportService creditReportService, ScontentService sContentService, SSearchService sSearchService, BgdzServiceImpl bgdzService) {
		this.filePath = filePath;
		this.pdfJsPath = pdfJsPath;
		this.googlePath = googlePath;
		this.pdfPagePath = pdfPagePath;
		this.absolutepath = absolutepath;
		this.kId = kId;
		this.batchReportDetailEntity = batchReportDetailEntity;
		this.batchReportDetailService = batchReportDetailService;
		this.creditReportService = creditReportService;
		this.sContentService = sContentService;
		this.sSearchService = sSearchService;
		this.bgdzService = bgdzService;
	}

	/**
	 *
	 * @Function 任务执行
	 * @FileName CreateReportTask.java
	 * @MethodName call
	 * @return
	 * @throws Exception
	 * @Date 2018年10月23日 上午11:21:39
	 * @Author Min DongXv
	 *
	 */
	@Override
	public CreateReportResult call() throws Exception {
		CreateReportResult result = null;
		if (null != batchReportDetailEntity) {
			if (StringUtils.isEmpty(batchReportDetailEntity.getTybm())) {
				// 没有tybm不能生成报告
				batchReportDetailService.updateDetailStatus(batchReportDetailEntity.getId(), 1, 5);
			} else {
				try {
					// 默认报告状态为生成成功
					int reportStatus = 3;
					// 使用同步返回的转换方法
					/*boolean status = HtmlToPdfUtils.googleConventSync(pdfJsPath,
							pdfPagePath + "/tybm=" + batchReportDetailEntity.getTybm() + "/kId=" + kId + "/keyword="
									+ batchReportDetailEntity.getA000001(),
							filePath, batchReportDetailEntity.getReportName(), null, true, googlePath);
*/
					Map<String, Object> templateData = this.getTemplateData(batchReportDetailEntity.getTybm(), kId);
					templateData.put("firstTitle", batchReportDetailEntity.getA000001());
					boolean status = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_template_freemarker.html", filePath, batchReportDetailEntity.getReportName(), absolutepath);

					// 命令未成功推出，修改报告状态为生成失败
					if (!status) {
						reportStatus = 4;
					}
					// 更新报告详情的状态
					batchReportDetailService.updateDetailStatus(batchReportDetailEntity.getId(), reportStatus, 5);
					// 构造返回实体
					result = new CreateReportResult(batchReportDetailEntity.getId(), reportStatus,
							batchReportDetailEntity.getBatchId());
				} catch (Exception e) {
					ExceptionLogger.error("CreateReportTask#call", "报告生成异常，ERROR:" + e.getMessage(), e);
					result = new CreateReportResult(batchReportDetailEntity.getId(), 4,
							batchReportDetailEntity.getBatchId());
				}
			}
		}
		return result;
	}

	/**
	 * 获取生成PDF需要的数据
	 * @param tybm
	 * @param kId
	 * @return
	 */
	private Map<String, Object> getTemplateData(String tybm, String kId) {
		Map<String, Object> result = new HashMap<String, Object>();

		String number = creditReportService.getReportSerials(kId, DateUtils.getCurrentTime());
		Map<String, Object> detail = sContentService.getDetail(kId, tybm, "XYHC", null);
		Map<String, List<TableResult>> map = new HashMap<String, List<TableResult>>();
		List<TableResult> assembleTableComponent = sSearchService.assembleTableComponent((List<TableResult>) detail.get("results"));

		StringBuilder catalogList = new StringBuilder();
		StringBuilder tableList = new StringBuilder();
		for (TableResult tableResult : assembleTableComponent) {
			String categoryCode = tableResult.getCategoryCode();
			if (map.containsKey(categoryCode)) {
				List<TableResult> list = map.get(categoryCode);
				list.add(tableResult);
			} else {
				List<TableResult> rs = new ArrayList<TableResult>();
				rs.add(tableResult);
				map.put(categoryCode, rs);
			}
		}

		int index = 0;
		for(String key : map.keySet()) {
			index ++;
			List<TableResult> trList = map.get(key);
			for(int i =0; i<trList.size(); i++) {
				TableResult tableResult = trList.get(i);
				if (i == 0) {
					catalogList.append("<div>").append(index).append(tableResult.getCategoryName()).append("</div><p>");
					tableList.append("<h3><span>").append(tableResult.getCategoryName()).append("</span></h3>");
				}
				tableList.append("<div class=\"tableL\"><h4>").append(tableResult.getTableNameCN()).append("</h4>").append(tableResult.getTableComponent()).append("</div>");
				if (i == trList.size()-1) {
					catalogList.append("<span>").append(tableResult.getTableNameCN()).append("</span>");
				} else {

					catalogList.append("<span>").append(tableResult.getTableNameCN()).append("、</span>");
				}
			}
			catalogList.append("</p>");

		}

		Hcbg latest = bgdzService.getLatest();
		latest.setReportNo(latest.getReportNo() + DateUtils.getStringOfTodayDate(DateUtils.SIMPLE_PATTERN) + number);
		result.put("firstReportNum", latest.getReportNo());
		result.put("reportProducer", latest.getReportProducer());
		result.put("reportDate", DateUtils.getStringOfTodayDate("yyyy年MM月dd日"));
		result.put("reportStatment", latest.getReportStatment());

		result.put("catalogList", catalogList.toString());
		result.put("tableList", tableList.toString());
		if (StringUtils.isNotBlank(latest.getWatermarker())) {
			result.put("waterPath", latest.getWatermarker().substring(0, latest.getWatermarker().lastIndexOf("/") + 1));
			result.put("water", latest.getWatermarker().substring(latest.getWatermarker().lastIndexOf("/") + 1));
		}
		return result;
	}
}